package com.farsight.leo.fssmartlock.mqtt;

import com.farsight.leo.fssmartlock.Constants;
import com.farsight.leo.fssmartlock.R;
import com.farsight.leo.fssmartlock.bases.BaseApplication;
import com.farsight.leo.fssmartlock.utils.LogUtils;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * Author: Administrator
 * Date: 2019/9/19
 * Project: SmartLockApp
 * Description:
 */
public class MqttConnection {
    private MqttAndroidClient mClient;
    private String topic;

    public MqttConnection() {
        StringBuilder sb = new StringBuilder();
        sb.append(BaseApplication.getUserData().getUser_name())
                .append('@')
                .append(System.currentTimeMillis())
                .append('@')
                .append(BaseApplication.acquireBaseContext().getString(R.string.app_name));
        topic = sb.toString();


    }


    public void connect(final Callback callback) {
        disconnect();

        mClient = new MqttAndroidClient(
                BaseApplication.acquireBaseContext(),
                Constants.MQTT_SERVER_URL, topic);

        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setConnectionTimeout(0);
        try {
            mClient.connect(
                    options,
                    BaseApplication.acquireBaseContext(),
                    new IMqttActionListener() {
                        @Override
                        public void onSuccess(IMqttToken asyncActionToken) {
                            //                            semaphore.release();
                            callback.onConnectSuccess(asyncActionToken);
                            try {
                                mClient.subscribe(Constants.SUBSCRIBE_TOPIC, 0);
                                mClient.setCallback(callback);
                            } catch (MqttException e) {
                                e.printStackTrace();
                                callback.onError("error when subscribe :" + e.getMessage());
                            }

                        }

                        @Override
                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                            //                            semaphore.release();
                            callback.onError(exception.getMessage());
                        }
                    });
        } catch (MqttException e) {
            e.printStackTrace();
            callback.onError("error when trying to establish new connection.");
        }

    }

    public IMqttDeliveryToken publish(String macAddress, String title, String content) throws MqttException {
        MqttMessage message = new MqttMessage();
        message.setQos(0);
        message.setRetained(false);
        message.setPayload((macAddress + "%%%&&&" + title + "%%%&&&" + content).getBytes());
        LogUtils.log("publish:"+new String(message.getPayload()));
        return mClient.publish(Constants.PUBLISH_TOPIC, message);
    }

    public void clearLastRetainMsg() throws MqttException {
        if(mClient==null){
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setQos(0);
        message.setPayload(new byte[0]);
        message.setRetained(true);
        mClient.publish(Constants.PUBLISH_TOPIC, message);
    }

    //    private void unsubscribe() throws MqttException {
    //        if (mClient != null) {
    //            mClient.unsubscribe(Constants.SUBSCRIBE_TOPIC);
    //        }
    //    }

    public void disconnect() {
        try {
            //            unsubscribe();
            if (mClient != null) {
                mClient.close();
                mClient.disconnect();
                mClient = null;
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public interface Callback extends MqttCallback {
        void onError(String msg);

        void onConnectSuccess(IMqttToken asyncActionToken);
    }


}
